package org.acghub.mtdb.common;


import com.alibaba.fastjson2.JSONObject;
import org.acghub.mtdb.common.type.TypeDateTime;
import org.bson.Document;

import java.time.LocalDateTime;

/**
 * @author zhouhe
 */
public final class MarshalUtil {

    public static final String GET = MarshalUtil.class.getName() + ".get";

    public static <T> T get(Document document, String key, Class<T> clazz) {
        if (clazz.equals(Byte.class) || clazz.equals(byte.class)) {
            return (T) Byte.valueOf(document.get(key, Number.class).byteValue());
        } else if (clazz.equals(Short.class) || clazz.equals(short.class)) {
            return (T) Short.valueOf(document.get(key, Number.class).shortValue());
        } else if (clazz.equals(Float.class) || clazz.equals(float.class)) {
            return (T) Float.valueOf(document.get(key, Number.class).floatValue());
        } else if (clazz.equals(LocalDateTime.class) || clazz.equals(TypeDateTime.class)) {
            return (T) TypeDateTime.parse(document.getString(key));
        }
        return document.get(key, clazz);
    }


    public static <T> T get(JSONObject jo, String key, Class<T> clazz) {
        if (clazz.equals(LocalDateTime.class) || clazz.equals(TypeDateTime.class)) {
            return (T) TypeDateTime.parse(jo.getString(key));
        }
        return jo.getObject(key, clazz);
    }
}
